package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"sync"
	"time"

	"github.com/gorilla/mux"
)

type Reminder struct {
	ID        string    `json:"id"`
	CreatorID string    `json:"creator_id"`
	Content   string    `json:"content"`
	RemTime   time.Time `json:"remind_time"`
}

var reminders = struct {
	sync.RWMutex
	store map[string][]Reminder
}{store: make(map[string][]Reminder)}

func main() {
	r := mux.NewRouter()
	r.HandleFunc("/reminders", createReminder).Methods("POST")
	r.HandleFunc("/reminders/{creator_id}", getReminders).Methods("GET")
	r.HandleFunc("/reminders/{creator_id}/{id}", deleteReminder).Methods("DELETE")
	r.HandleFunc("/reminders/{creator_id}/{id}", updateReminder).Methods("PUT")

	http.ListenAndServe(":8080", r)
}

func createReminder(w http.ResponseWriter, r *http.Request) {
	var reminder Reminder
	if err := json.NewDecoder(r.Body).Decode(&reminder); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	if reminder.CreatorID == "" {
		http.Error(w, "Missing CreatorID", http.StatusBadRequest)
		return
	}

	reminder.ID = generateID() // 生成唯一 ID

	reminders.Lock()
	defer reminders.Unlock()

	if _, exists := reminders.store[reminder.CreatorID]; !exists {
		reminders.store[reminder.CreatorID] = []Reminder{}
	}

	reminders.store[reminder.CreatorID] = append(reminders.store[reminder.CreatorID], reminder)

	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(reminder)
}

func generateID() string {
	return fmt.Sprintf("%d", time.Now().UnixNano()) // 生成基于时间的唯一 ID
}

func getReminders(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	creatorID := vars["creator_id"]

	reminders.RLock()
	reminderList, exists := reminders.store[creatorID]
	reminders.RUnlock()

	if !exists {
		http.Error(w, "No reminders found", http.StatusNotFound)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(reminderList)
}

func deleteReminder(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	creatorID := vars["creator_id"]
	id := vars["id"]

	reminders.Lock()
	defer reminders.Unlock()

	if _, exists := reminders.store[creatorID]; exists {
		for i, reminder := range reminders.store[creatorID] {
			if reminder.ID == id {
				reminders.store[creatorID] = append(reminders.store[creatorID][:i], reminders.store[creatorID][i+1:]...)
				w.WriteHeader(http.StatusNoContent)

			}
		}
	}
	http.Error(w, "Reminder not found", http.StatusNotFound)
}

func updateReminder(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	creatorID := vars["creator_id"]
	id := vars["id"]

	var updated Reminder
	if err := json.NewDecoder(r.Body).Decode(&updated); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	reminders.Lock()
	defer reminders.Unlock()

	if remindersList, exists := reminders.store[creatorID]; exists {
		for i, reminder := range remindersList {
			if reminder.ID == id {
				updated.ID = id
				updated.CreatorID = creatorID
				reminders.store[creatorID][i] = updated
				w.WriteHeader(http.StatusNoContent) // 204 No Content
				return
			}
		}
	}
	http.Error(w, "Reminder not found", http.StatusNotFound)
}
